package com.kreao.korean.service;

import com.kreao.korean.service.interfaces.UserService;

import com.kreao.korean.entity.User;
import com.kreao.korean.exception.ResourceNotFoundException;
import com.kreao.korean.repository.StudyRecordRepository;
import com.kreao.korean.repository.UserRepository;
import com.kreao.korean.repository.WordRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service("userServiceImpl")
@RequiredArgsConstructor
@Transactional
public class UserServiceImpl implements UserService {
    
    private final UserRepository userRepository;
    private final WordRepository wordRepository;
    private final StudyRecordRepository studyRecordRepository;
    
    @Override
    @Transactional(readOnly = true)
    public User getUserById(Long userId) {
        return userRepository.findById(userId)
            .orElseThrow(() -> new ResourceNotFoundException("User", "id", userId));
    }
    
    @Override
    public User updateUser(Long userId, User userRequest) {
        User existingUser = getUserById(userId);
        
        // 更新允许修改的字段
        if (userRequest.getNickname() != null) {
            existingUser.setNickname(userRequest.getNickname());
        }
        if (userRequest.getBio() != null) {
            existingUser.setBio(userRequest.getBio());
        }
        if (userRequest.getAvatar() != null) {
            existingUser.setAvatar(userRequest.getAvatar());
        }
        
        return userRepository.save(existingUser);
    }
    
    @Override
    @Transactional(readOnly = true)
    public UserOverview getUserOverview(Long userId) {
        User user = getUserById(userId);
        
        LocalDateTime startOfDay = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        
        Long totalWords = wordRepository.countByUserId(userId);
        Long todayStudyCount = studyRecordRepository.countByUserIdAndStudyTimeAfter(userId, startOfDay);
        Long favoriteWords = wordRepository.findByUserIdAndIsFavorite(userId, true, null).getTotalElements();
        
        return new UserOverview(
            user,
            totalWords,
            (long) user.getStudyDays(),
            user.getAccuracy(),
            todayStudyCount,
            favoriteWords
        );
    }
} 